package com.peng.rpc.provider;

import com.peng.rpc.enumeration.RpcError;
import com.peng.rpc.exception.RpcException;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 默认的服务注册表实现
 *
 * 假设X.Y接口有一个实现类A，那么就可以说A是X，Y接口的实际实现实例。
 * @author Wonderson
 * @email wpp.ds@foxmail.com
 * @date 2022/2/28 19:34
 */
@Slf4j
public class DefaultServiceProvider implements ServiceProvider {

    private static final Map<String, Object> serviceMap = new ConcurrentHashMap<>();
    private static final Set<String> registeredServices = ConcurrentHashMap.newKeySet();

    @Override
    public synchronized <T> void addService(T service,String serviceName) {
        if (registeredServices.contains(serviceName)) {
            return; //服务已经注册
        }
        registeredServices.add(serviceName);
        Class<?>[] interfaces = service.getClass().getInterfaces();
        serviceMap.put(serviceName, service);
        log.info("给远程接口【{}】注册一个服务：【{}】", Arrays.toString(interfaces), serviceName);
    }

    @Override
    public Object getService(String serviceName) {
        if (!serviceMap.containsKey(serviceName)) {
            throw new RpcException(RpcError.SERVICE_NOT_FOUND);
        }
        return serviceMap.get(serviceName);
    }
}
